/**
 * 网络请求
 * @author yxk
 */
import App from '../main.js'
import { BASE_URL_FN } from '../config.js'

let loadingCount = 0

const closeLoading = () => {
	if (loadingCount <= 0) {
		loadingCount = 0
		uni.hideLoading();
	}
}

const service = (config) => {
	if (!config.hideLoading && loadingCount === 0) {
		uni.showLoading({
			mask: true,
			title: '加载中'
		})
	}
	loadingCount++
	if (!config.header) {
		config.header = {}
	}
	if (config.requestType === 'form') {
		config.header = {
			...config.header,
			'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
		}
	}

	const token = uni.getStorageSync('token') || null
  const flag = config.hasOwnProperty('requiredAuth') ? !!config.requiredAuth : true

	if (token) {
		config.header = {
			...config.header,
			'Admin-Token': token,
			'Authentication': token
		}
	} else if (flag) {
		// 非登录相关接口，没有 token 直接转到登录页
		loadingCount = 0
		uni.hideLoading()
		App.$Router.reLaunch('/pages_login/index')
		return Promise.reject()
	}

	let url = ''
	if (!config.url.startsWith('http')) {
		url = BASE_URL_FN() + config.url
	} else {
		url = config.url
	}

	const appid = uni.getStorageSync('appid') || null
	if (appid) {
		config.header.k = appid
	}

	// #ifdef H5
	config.withCredentials = true
	// #endif

	return new Promise((resolve, reject) => {
		uni.request({
			...config,
			url,
			success: res => {
				loadingCount--
				closeLoading()
				const data = res.data
				if (config.responseType === 'arraybuffer') {
					resolve({ code: data.code || 200, data: res })
					return
				}
				if (data.code === 302) {
					handleLoginExpired(data)
					reject('登录已失效，请重新登录')
					return
				}
				if (data.code === 0 || data.code === 200) {
					// 返回一个对象，包含 code 和 data
					resolve({ 
						code: data.code, 
						data: data.hasOwnProperty('data') ? data.data : data,
						pageInfo: {
							count:data.count,
							limit:data.limit,
							page:data.page
						} ,
						})
				} else {
					App.$toast(data.msg)
					reject({ code: data.code, msg: data.msg })
				}
			},
			fail: error => {
				loadingCount--
				closeLoading()
				reject(error)
			}
		})
	})

	function handleLoginExpired(data) {
		App.$Router.reLaunch('/pages/login/index')
		let str = ''
		if (data.extra && data.extra === 1) {
			str = `您的账号${data.extraTime}在别处登录。如非本人操作，则密码可能已泄漏，建议修改密码`
		} else {
			str = '登录已失效，请重新登录'
		}
		setTimeout(() => {
			App.$toast(str)
			str = null
		}, 500)
	}
}

export default service